﻿using IceDog.HiDocs.Models;
using IceDog.RabbitMQ.ConfigurationService.Factories;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
using RabbitMQ.Client.MessagePatterns;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IceDog.HiDocs.Consumer
{
    public static class MainApplication
    {
        public static void Run()
        {
            try
            {
                var connectionFactory = FactoryProvider.GetRMQFactory();
                using (var connection = connectionFactory.CreateConnection("hidocs.connection"))
                {
                    
                    using (var channel = connection.CreateModel())
                    {
                        // 这指示通道不预取超过1个消息
                        channel.BasicQos(0, 1, false);
                        //创建一个新的，持久的队列
                        var queueName = $"hidocs.queue";
                        channel.QueueDeclare(queue: queueName, durable: false, exclusive: true, autoDelete: true, arguments: null);

                        var exchangeName = "hidocs.exchange";
                        var routingKey = "hidocs.routingKey";
                        channel.QueueBind(queue:queueName,exchange: exchangeName,routingKey: routingKey);

                        using (var subscription = new Subscription(channel, queueName, false))
                        {
                            Console.WriteLine("等待消息...");
                            var encoding = new UTF8Encoding();
                            while (channel.IsOpen)
                            {
                                BasicDeliverEventArgs eventArgs;
                                var success = subscription.Next(2000, out eventArgs);
                                if (!success) { continue; }
                                var msgBytes = eventArgs.Body;
                                var message = encoding.GetString(msgBytes);
                                var model =JsonConvert.DeserializeObject<MessageModel>(message);
                                Console.WriteLine(model.Title+"-"+model.DocType.ToString());
                                channel.BasicAck(eventArgs.DeliveryTag, false);
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生了错误：" + ex);
                throw;
            }
        }
    }
}
